<template>
  <view class="app-avatar-upload">
    <!-- 标题和说明 -->
    <view class="upload-header">
      <view class="header-title">
        <u-icon name="photo" color="#409eff" size="16"></u-icon>
        <text class="title-text">{{ title }}</text>
        <text v-if="required" class="required">*</text>
      </view>
      <view v-if="tip" class="upload-tip">{{ tip }}</view>
    </view>

    <!-- 头像上传区域 -->
    <view class="avatar-upload-area">
      <view class="avatar-container">
        <!-- 已上传的头像 -->
        <view 
          v-if="avatarList.length > 0"
          class="avatar-preview"
          @click="previewAvatar"
        >
          <image 
            :src="avatarList[0].url" 
            mode="aspectFill" 
            class="avatar-image"
          ></image>
          <view class="avatar-edit-overlay">
            <u-icon name="camera" color="#fff" size="20"></u-icon>
            <text class="edit-text">点击更换</text>
          </view>
          <!-- 删除按钮 -->
          <view class="delete-btn" @click.stop="removeAvatar">
            <u-icon name="close" color="#fff" size="12"></u-icon>
          </view>
          <!-- 上传进度指示器 -->
          <view v-if="avatarList[0].uploading" class="upload-progress">
            <u-loading-icon mode="circle" size="20"></u-loading-icon>
          </view>
        </view>

        <!-- 添加头像按钮 -->
        <view 
          v-else
          class="avatar-upload-btn"
          @click="chooseAvatar"
        >
          <u-icon name="plus" color="#999" size="32"></u-icon>
          <text class="upload-text">{{ addButtonText }}</text>
        </view>
      </view>
    </view>

    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-message">
      <u-icon name="error-circle" color="#f56c6c" size="14"></u-icon>
      <text class="error-text">{{ errorMessage }}</text>
    </view>
  </view>
</template>

<script>
import { ref, watch } from 'vue'
import { userInfoApi } from '@/api/user'
import { formatAvatarForDisplay } from '@/utils/avatarUtils'

export default {
  name: 'AppAvatarUpload',
  
  props: {
    // 头像列表
    modelValue: {
      type: Array,
      default: () => []
    },
    // 标题
    title: {
      type: String,
      default: '头像'
    },
    // 提示文字
    tip: {
      type: String,
      default: '请上传头像图片，支持jpg、jpeg、png格式，最大2MB'
    },
    // 是否必填
    required: {
      type: Boolean,
      default: false
    },
    // 添加按钮文字
    addButtonText: {
      type: String,
      default: '上传头像'
    },
    // 图片大小限制（MB）
    maxSize: {
      type: Number,
      default: 2
    },
    // 允许的图片类型
    allowedTypes: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png']
    }
  },

  emits: ['update:modelValue', 'change', 'success', 'error', 'remove'],

  setup(props, { emit }) {
    const avatarList = ref([...props.modelValue])
    const errorMessage = ref('')

    // 监听modelValue变化
    watch(() => props.modelValue, (newVal) => {
      avatarList.value = [...newVal]
    }, { deep: true })

    // 监听avatarList变化，同步到父组件
    watch(avatarList, (newVal) => {
      emit('update:modelValue', [...newVal])
      emit('change', [...newVal])
    }, { deep: true })

    // 上传头像到服务器
    const uploadAvatar = async (filePath) => {
      try {
        console.log('开始上传头像:', filePath)
        
        // 创建临时头像对象，标记为上传中
        const tempAvatar = {
          url: filePath,
          uploading: true,
          error: false
        }
        
        // 清空之前的头像，只保留当前上传的
        avatarList.value = [tempAvatar]
        
        // 调用用户头像上传API，传递正确的上传类型和来源
        const result = await userInfoApi.uploadAvatar(filePath, 'USER_AVATAR', 'APP', '用户头像')
        
        console.log('头像上传结果:', result)
        
        if (result && result.code === 200 && result.data) {
          // 上传成功，更新头像信息
          const uploadedAvatar = {
            id: result.data.id || Date.now(),
            url: result.data.fileUrl || result.data.url, // 兼容不同的返回格式
            fileName: result.data.fileName,
            fileSize: result.data.fileSize,
            fileType: result.data.fileType,
            fileExtension: result.data.fileExtension,
            uploadType: 'USER_AVATAR',
            uploadSource: 'APP',
            uploading: false,
            error: false
          }
          
          // 更新头像列表
          avatarList.value = [uploadedAvatar]
          
          // 创建完整的文件信息对象，用于存储到数据库
          const fileInfo = {
            id: uploadedAvatar.id,
            status: 'success',
            fileUrl: uploadedAvatar.url,
            fileName: uploadedAvatar.fileName,
            filePath: result.data.filePath || uploadedAvatar.url,
            fileSize: uploadedAvatar.fileSize,
            fileType: uploadedAvatar.fileType,
            createTime: new Date().toISOString(),
            uploadType: uploadedAvatar.uploadType,
            uploadSource: uploadedAvatar.uploadSource,
            fileExtension: uploadedAvatar.fileExtension,
            originalFileName: result.data.originalFileName || uploadedAvatar.fileName
          }
          
          console.log('头像上传成功:', uploadedAvatar)
          console.log('文件信息对象:', fileInfo)
          
          // 发送成功事件，传递文件信息对象
          emit('success', [fileInfo])
          clearError()
          
          return fileInfo
        } else {
          throw new Error(result?.message || '上传失败')
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        
        // 标记上传失败
        if (avatarList.value.length > 0) {
          avatarList.value[0].uploading = false
          avatarList.value[0].error = true
        }
        
        showError(error.message || '头像上传失败')
        emit('error', error)
        
        return null
      }
    }

    // 选择头像
    const chooseAvatar = () => {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          console.log('选择头像成功:', res)
          
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            const tempFilePath = res.tempFilePaths[0]
            
            // 简化验证逻辑，主要检查文件大小
            const validation = validateImage({ path: tempFilePath })
            if (validation.valid) {
              await uploadAvatar(tempFilePath)
            } else {
              showError(validation.message)
            }
          } else {
            showError('未获取到头像文件')
          }
        },
        fail: (error) => {
          console.error('选择头像失败:', error)
          showError('选择头像失败')
        }
      })
    }

    // 预览头像
    const previewAvatar = () => {
      if (avatarList.value.length > 0) {
        const avatar = avatarList.value[0]
        uni.previewImage({
          urls: [avatar.url],
          current: avatar.url
        })
      }
    }

    // 删除头像
    const removeAvatar = () => {
      avatarList.value = []
      emit('remove')
    }

    // 验证图片
    const validateImage = (file) => {
      console.log('开始验证文件:', file)
      
      // 检查文件大小
      if (file.size && file.size > props.maxSize * 1024 * 1024) {
        return {
          valid: false,
          message: `图片大小不能超过${props.maxSize}MB`
        }
      }
      
      // 简化文件类型验证 - 由于uni-app已经通过系统文件选择器过滤了文件类型
      // 这里主要检查文件大小，文件类型验证由系统API和后端处理
      console.log('文件验证通过，文件路径:', file.path)
      return { valid: true }
    }

    // 显示错误信息
    const showError = (message) => {
      errorMessage.value = message
      setTimeout(() => {
        errorMessage.value = ''
      }, 3000)
    }

    // 清除错误信息
    const clearError = () => {
      errorMessage.value = ''
    }

    return {
      avatarList,
      errorMessage,
      chooseAvatar,
      previewAvatar,
      removeAvatar
    }
  }
}
</script>

<style lang="scss" scoped>
.app-avatar-upload {
  .upload-header {
    margin-bottom: 16rpx;
    
    .header-title {
      display: flex;
      align-items: center;
      margin-bottom: 8rpx;
      
      .title-text {
        margin-left: 8rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
      }
      
      .required {
        color: #f56c6c;
        margin-left: 4rpx;
      }
    }
    
    .upload-tip {
      font-size: 24rpx;
      color: #999;
      line-height: 1.4;
    }
  }

  .avatar-upload-area {
    .avatar-container {
      display: flex;
      justify-content: center;
      
      .avatar-preview {
        position: relative;
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        overflow: hidden;
        cursor: pointer;
        
        .avatar-image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
        
        .avatar-edit-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;
          
          .edit-text {
            color: #fff;
            font-size: 20rpx;
            margin-top: 4rpx;
          }
        }
        
        &:hover .avatar-edit-overlay {
          opacity: 1;
        }
        
        .delete-btn {
          position: absolute;
          top: 4rpx;
          right: 4rpx;
          width: 32rpx;
          height: 32rpx;
          background-color: rgba(0, 0, 0, 0.6);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }
        
        .upload-progress {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.3);
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      
      .avatar-upload-btn {
        width: 120rpx;
        height: 120rpx;
        border: 2rpx dashed #ddd;
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: border-color 0.3s ease;
        
        &:hover {
          border-color: #409eff;
        }
        
        .upload-text {
          font-size: 20rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }
    }
  }

  .error-message {
    display: flex;
    align-items: center;
    margin-top: 16rpx;
    padding: 12rpx 16rpx;
    background-color: #fef0f0;
    border: 1rpx solid #fbc4c4;
    border-radius: 8rpx;
    
    .error-text {
      margin-left: 8rpx;
      font-size: 24rpx;
      color: #f56c6c;
    }
  }
}
</style>
